package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    // 修复TAG初始化问题
    private static final String TAG = "MainActivity";
    private TextView tv;
    private Timer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        // 窗口边距处理
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 初始化UI组件
        tv = findViewById(R.id.txtout);
        tv.setText("你好");

        EditText input = findViewById(R.id.inp);
        String s = input.getText().toString();

        // 日志输出
        Log.i("mytag", "onCreate: 111111111111111111");
        Log.d(TAG, "输入框初始内容: " + s);
        Log.i(TAG, "onCreate() called");

        // 跳转按钮事件
        Button btnJump = findViewById(R.id.btn_jump);
        btnJump.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, MainActivity1.class);
            startActivity(intent);
        });

        // 初始化定时任务（每秒执行）
        initTimerTask();
    }

    void initTimerTask() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 在主线程更新UI
                runOnUiThread(() -> {
                    Log.d(TAG, "定时任务执行 - 当前时间: " + System.currentTimeMillis());
                    // 在此添加需要定时执行的任务逻辑
                });
            }
        }, 1000, 1000); // 延迟1秒后开始，每秒执行一次
    }

    public void mybtnClick(View v) {
        Log.i(TAG, "按钮点击事件触发");

        EditText myinput = findViewById(R.id.inp);
        String s2 = myinput.getText().toString();
        tv.setText("Good Luck " + s2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放定时任务资源
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
            Log.d(TAG, "定时任务已取消");
        }
    }
}